package us.styx.net.codec;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;

import us.styx.net.Client;

public class LoginProtocolDecoder implements CummulativeProtocolDecoder {
    
    @Override
    public void decode(Client client) throws IOException {
	client.setLoginState(LoginState.INITIAL);
	client.getChannel().read(client.getBuffer());
	client.getBuffer().flip();
        try {
           switch (client.getLoginState()) {
           
	    case INITIAL:
		if (client.getBuffer().remaining() < 2) {
		    client.getBuffer().compact();
		    return;
		}
		int initial = client.getBuffer().get() & 0xFF;
		System.out.println("" + initial);
		int loginServer = client.getBuffer().get() & 0xFF;
		System.out.println("" + loginServer);
		client.setLoginState(LoginState.KEY_EXCHANGE);
		break;
        	
            case KEY_EXCHANGE:
        	ByteBuffer keys = ByteBuffer.allocateDirect(17);
        	keys.putLong(0);
        	keys.put((byte) 0);
        	keys.putLong(new SecureRandom().nextLong());
        	client.getChannel().write(keys);
        	client.setLoginState(LoginState.HANDSHAKE);
        	break;
        	
            case HANDSHAKE:

        	break;
	    
            case LOGIN:
        	break;
	    
           }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    
    public enum LoginState {
	INITIAL, 
	KEY_EXCHANGE, 
	HANDSHAKE,
	LOGIN
    }
}